var mysql = require('mysql');
const bodyParser = require('koa-bodyparser')
const koa = require('koa')
const koaRouter = require('koa-router')
const router = koaRouter()
const app = new koa()
const multer = require('koa-multer') //解析图片
const path = require('path')
const port = 4000

// var upload = multer({ dest: 'uploads/' })  //dest只能写地址
var storage = multer.diskStorage({ //能穿很多参数
    destination: function (req, file, cb) {
      cb(null, 'uploads')
    },
    filename: function (req, file, cb) {
        // console.log(111,file)
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
      let fixStr = file.mimetype.split('/')[1] //手动改成图片
      cb(null, file.fieldname + '-' + uniqueSuffix +'.' + fixStr)
    }
  })
  
  var upload = multer({ storage: storage })

var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'wangyiyun'
  });
  connection.connect();

app.use(bodyParser())
app.use(router.routes())
app.use(router.allowedMethods())

router.post('/getimg', upload.single('img'), async (ctx, next) =>{
    try{ 
        console.log(111,ctx.req.file) //图片信息
        const url =  path.join(__dirname, ctx.req.file.path)
        const filename = ctx.req.file.filename
        console.log('拼接后的路径', url)
        // console.log(filename)
        //把图片信息写入数据库
        await new Promise((reslove, reject) =>{
            connection.query('insert into imgs set ?',{url,filename, status:1},(err,results) =>{
                if(err) reject(err)
                reslove(results)
                console.log(222,results)
            })
        })
        ctx.body={
            code:1,
            msg:'上传成功'
        }
    }catch(e){
        ctx.body={
            code:0,
            msg:'上传失败'
        }
    }
  })
//获取轮播图
router.get('/lunbo', async(ctx, next) => {
    try {
        const data = await new Promise((resolve, reject) => {
            connection.query('select * from imgs', (err, results) =>{
                if(err) reject(err)
                resolve(results)
            })
        })
        ctx.body = {
            code: 1,
            msg: data
        }
    } catch(e) {
        ctx.body = {
            code: 0,
            msg: '没有'
        }
    }
})

//注册到数据库
router.post('/login',async(ctx,next)=>{
    try{
        const {phone,password} = ctx.request.body
        console.log(ctx.request.body)
        const data = await new Promise((resolve,reject) =>{
            connection.query('select * from users where phone=?',phone,(error,results) =>{ //准确查找
                if(error) reject (error)
                console.log(111,results)
                resolve(results)
            })
        })
        if(data.length === 0){ //如果数据库是空
            await new Promise((resolve, reject) =>{
                connection.query('insert into users set ?', {phone, password},(error, results) =>{ //写入数据库
                    if (error) reject (error);
                    console.log(results);
                    resolve(results)
                })
            })
            ctx.body={
                code:1,
                msg:'注册成功'
            }
        }else{
            ctx.body={
                code:0,
                msg:'该用户已存在'
            }
        }       
    }catch(error){
        ctx.body = {
            code: 0,
            msg: 1
        }
    }
})
//登录
router.post('/enter',async(ctx,next) =>{
    const {phone,password} = ctx.request.body
    console.log(ctx.request.body)
    console.log(phone,password)
    try{
        const data = await new Promise((resolve,reject) =>{
            connection.query('select * from users where phone=? and password=?',[phone,password],(e,results) =>{
                if(e) reject(e)
                console.log(111,results)
                resolve(results)
            })
        })
        // console.log(data)
        if(data.length === 0){
            ctx.body={
                code:0,
                msg:'去注册'
            }
        }else if(data.some(item => item.phone== phone && item.password==password)){
            ctx.body={
                code:1,
                msg:'登陆成功'
            }
        }
    }catch(e){
        ctx.body={
            code:0,
            msg:'登陆失败'
        }
    }
    
})
//列表

//工作人员注册
router.post('/worklogin',async(ctx,next)=>{
    try{
        const {phone,password} = ctx.request.body
        console.log(phone,password)
        const data = await new Promise((resolve,reject) =>{
            connection.query('select * from workusers where phone=?',phone,(error,results) =>{ //准确查找
                if(error) reject (error)
                console.log(111,results)
                resolve(results)
            })
        })
        if(data.length === 0){ //如果数据库是空
            await new Promise((resolve, reject) =>{
                connection.query('insert into workusers set ?', {phone, password},(error, results) =>{ //写入数据库
                    if (error) reject (error);
                    console.log(results);
                    resolve(results)
                })
            })
            ctx.body={
                code:1,
                msg:'注册成功'
            }
        }else{
            ctx.body={
                code:0,
                msg:'该用户已存在'
            }
        }       
    }catch(error){
        ctx.body = {
            code: 0,
            msg: 1
        }
    }
})
//工作人员登录
router.post('/workenter',async(ctx,next) =>{
    const {phone,password} = ctx.request.body
    console.log(ctx.request.body)
    console.log(phone,password)
    try{
        const data = await new Promise((resolve,reject) =>{
            connection.query('select * from workusers where phone=? and password=?',[phone,password],(e,results) =>{
                if(e) reject(e)
                console.log(111,results)
                resolve(results)
            })
        })
        // console.log(data)
        if(data.length === 0){
            ctx.body={
                code:0,
                msg:'去注册'
            }
        }else if(data.some(item => item.phone== phone && item.password==password)){
            ctx.body={
                code:1,
                msg:'登陆成功'
            }
        }
    }catch(e){
        ctx.body={
            code:0,
            msg:'登陆失败'
        }
    }
    
})
app.listen(port, () => {
    console.log('正在监听端口' + port, 'http://localhost:' + port)
})